package com.woniuxy.auth.shiro;/*
@author houguai
@create 2021-03-03 12:05
*/

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.auth.entity.Roles_admin;
import com.woniuxy.auth.jwt.Audience;
import com.woniuxy.auth.jwt.JwtUtil;
import com.woniuxy.auth.mapper.Rbac_permMapper;
import com.woniuxy.auth.mapper.Roles_adminMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

//AuthorizingRealm 授权Realm

/**
 * 自定义的Realm，用于与数据库交互
 */
public class DBRealm extends AuthorizingRealm {



    private static final Logger logger= LoggerFactory.getLogger(DBRealm.class);
    @Autowired
    private Rbac_permMapper permMapper;
    @Autowired
    private Audience audience;

    @Autowired
    private Roles_adminMapper adminMapper;

    //获取授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

       logger.info("获取授权信息");

        String jwt = principals.getPrimaryPrincipal().toString();
        int id = JwtUtil.getUserId(jwt, audience.getBase64Secret());
        //封装角色信息
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addStringPermission("movie:add");
        permMapper.getPermsById(id).forEach(p->{
            info.addStringPermission(p.getCode());
        });

//        //封装权限信息
//        info.setStringPermissions(perms);
        return info;//返回给securityManger（subject）
    }

    //获取认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //token中包含了账号密码信息
        logger.info("调用realm的获取认证信息方法，得到对应用户的账号信息");
        UsernamePasswordToken uptoken =(UsernamePasswordToken) token;

        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("account",uptoken.getUsername());
        Roles_admin admin=adminMapper.selectOne(queryWrapper);
        //获取账号密码
//        String account=(String) token.getPrincipal();
//
//        String pwd=new String((char[]) token.getCredentials());
//        logger.info(account+","+pwd);

        //通过账号作为查询条件去数据库中查出对应的账号密码信息  调用service相关方法
        //模拟假设获得了账号密码
        //User user=new User().setAccount("zhangsan").setPwd("");


        if (admin==null){
            throw new UnknownAccountException("账号"+uptoken.getUsername()+"不存在");//报账号不存在异常
        }

        //将查询到的结果封装到AuthenticationInfo中返回给sercuritymanager，securitymanager会根据
        //AuthenticationInfo中的信息与token中的信息做比对  判断账号密码是否正确
        //参数1：查询到的账号
        //参数2：查询到的密码
        //参数3：当前relam的名字
        SimpleAuthenticationInfo info=
                new SimpleAuthenticationInfo(admin,admin.getPassword(),this.getName());

        return info;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }
}
